package com.laundry.user.data.database

import androidx.room.*
import androidx.lifecycle.LiveData
import kotlinx.coroutines.flow.Flow
import com.laundry.user.data.model.*

/**
 * 聊天数据访问对象
 */
@Dao
interface ChatDao {
    // 聊天会话相关
    @Query("SELECT * FROM chat_sessions WHERE user_id = :userId AND is_active = 1 ORDER BY updated_at DESC")
    fun getChatSessions(userId: String): Flow<List<ChatSession>>
    
    @Query("SELECT * FROM chat_sessions WHERE id = :sessionId")
    suspend fun getChatSessionById(sessionId: String): ChatSession?
    
    @Query("SELECT * FROM chat_sessions WHERE user_id = :userId AND merchant_id = :merchantId")
    suspend fun getChatSessionByUserAndMerchant(userId: String, merchantId: String): ChatSession?
    
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertChatSession(session: ChatSession)
    
    @Update
    suspend fun updateChatSession(session: ChatSession)
    
    @Query("UPDATE chat_sessions SET unread_count = 0 WHERE id = :sessionId")
    suspend fun markSessionAsRead(sessionId: String)
    
    // 聊天消息相关
    @Query("SELECT * FROM chat_messages WHERE session_id = :sessionId ORDER BY created_at ASC")
    fun getMessagesBySession(sessionId: String): Flow<List<ChatMessage>>
    
    @Query("SELECT * FROM chat_messages WHERE session_id = :sessionId ORDER BY created_at DESC LIMIT :limit")
    suspend fun getRecentMessages(sessionId: String, limit: Int): List<ChatMessage>
    
    @Query("SELECT * FROM chat_messages WHERE id = :messageId")
    suspend fun getMessageById(messageId: String): ChatMessage?
    
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertMessage(message: ChatMessage)
    
    @Update
    suspend fun updateMessage(message: ChatMessage)
    
    @Query("UPDATE chat_messages SET is_read = 1 WHERE session_id = :sessionId AND sender_id != :currentUserId")
    suspend fun markMessagesAsRead(sessionId: String, currentUserId: String)
    
    @Query("SELECT COUNT(*) FROM chat_messages WHERE session_id = :sessionId AND is_read = 0 AND sender_id != :currentUserId")
    suspend fun getUnreadMessageCount(sessionId: String, currentUserId: String): Int
    
    @Query("DELETE FROM chat_messages WHERE session_id = :sessionId")
    suspend fun deleteMessagesBySession(sessionId: String)
}

/**
 * 通知数据访问对象
 */
@Dao
interface NotificationDao {
    @Query("SELECT * FROM notifications WHERE user_id = :userId ORDER BY created_at DESC")
    fun getNotifications(userId: String): Flow<List<Notification>>
    
    @Query("SELECT * FROM notifications WHERE user_id = :userId AND is_read = 0 ORDER BY created_at DESC")
    fun getUnreadNotifications(userId: String): Flow<List<Notification>>
    
    @Query("SELECT COUNT(*) FROM notifications WHERE user_id = :userId AND is_read = 0")
    suspend fun getUnreadNotificationCount(userId: String): Int
    
    @Query("SELECT * FROM notifications WHERE id = :notificationId")
    suspend fun getNotificationById(notificationId: String): Notification?
    
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertNotification(notification: Notification)
    
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertNotifications(notifications: List<Notification>)
    
    @Update
    suspend fun updateNotification(notification: Notification)
    
    @Query("UPDATE notifications SET is_read = 1 WHERE id = :notificationId")
    suspend fun markAsRead(notificationId: String)
    
    @Query("UPDATE notifications SET is_read = 1 WHERE user_id = :userId")
    suspend fun markAllAsRead(userId: String)
    
    @Delete
    suspend fun deleteNotification(notification: Notification)
    
    @Query("DELETE FROM notifications WHERE user_id = :userId AND created_at < :beforeDate")
    suspend fun deleteOldNotifications(userId: String, beforeDate: String)
}

/**
 * 收藏数据访问对象
 */
@Dao
interface FavoriteDao {
    @Query("SELECT * FROM favorites WHERE user_id = :userId ORDER BY created_at DESC")
    fun getFavorites(userId: String): Flow<List<Favorite>>
    
    @Query("SELECT * FROM favorites WHERE user_id = :userId AND merchant_id = :merchantId")
    suspend fun getFavorite(userId: String, merchantId: String): Favorite?
    
    @Query("SELECT EXISTS(SELECT 1 FROM favorites WHERE user_id = :userId AND merchant_id = :merchantId)")
    suspend fun isFavorite(userId: String, merchantId: String): Boolean
    
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertFavorite(favorite: Favorite)
    
    @Query("DELETE FROM favorites WHERE user_id = :userId AND merchant_id = :merchantId")
    suspend fun deleteFavorite(userId: String, merchantId: String)
    
    @Query("SELECT COUNT(*) FROM favorites WHERE user_id = :userId")
    suspend fun getFavoriteCount(userId: String): Int
}

/**
 * 地址数据访问对象
 */
@Dao
interface AddressDao {
    @Query("SELECT * FROM addresses WHERE user_id = :userId ORDER BY is_default DESC, created_at DESC")
    fun getAddresses(userId: String): Flow<List<Address>>
    
    @Query("SELECT * FROM addresses WHERE user_id = :userId AND is_default = 1")
    suspend fun getDefaultAddress(userId: String): Address?
    
    @Query("SELECT * FROM addresses WHERE id = :addressId")
    suspend fun getAddressById(addressId: String): Address?
    
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertAddress(address: Address)
    
    @Update
    suspend fun updateAddress(address: Address)
    
    @Delete
    suspend fun deleteAddress(address: Address)
    
    @Query("UPDATE addresses SET is_default = 0 WHERE user_id = :userId")
    suspend fun clearDefaultAddress(userId: String)
    
    @Query("UPDATE addresses SET is_default = 1 WHERE id = :addressId")
    suspend fun setDefaultAddress(addressId: String)
}

/**
 * 搜索历史数据访问对象
 */
@Dao
interface SearchHistoryDao {
    @Query("SELECT * FROM search_history WHERE user_id = :userId ORDER BY last_search_time DESC LIMIT :limit")
    suspend fun getSearchHistory(userId: String, limit: Int = 10): List<SearchHistory>
    
    @Query("SELECT * FROM search_history WHERE user_id = :userId AND keyword = :keyword")
    suspend fun getSearchHistoryByKeyword(userId: String, keyword: String): SearchHistory?
    
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertSearchHistory(searchHistory: SearchHistory)
    
    @Update
    suspend fun updateSearchHistory(searchHistory: SearchHistory)
    
    @Query("DELETE FROM search_history WHERE user_id = :userId AND keyword = :keyword")
    suspend fun deleteSearchHistory(userId: String, keyword: String)
    
    @Query("DELETE FROM search_history WHERE user_id = :userId")
    suspend fun clearSearchHistory(userId: String)
    
    @Query("DELETE FROM search_history WHERE user_id = :userId AND id NOT IN (SELECT id FROM search_history WHERE user_id = :userId ORDER BY last_search_time DESC LIMIT :keepCount)")
    suspend fun limitSearchHistory(userId: String, keepCount: Int = 20)
}
